Skip to main content

Post Request

ב-Post Request נשתמש בדרך כלל כשאנחנו רוצים להוסיף מידע לתוך ה-DB.

כדי להוסיף ערכים ב-DB אנחנו בדרך כלל משתמשים בטפסים.

בדוגמא נשתמש ב-template forms ובהכנסה של פוסטים לרשימה.

לכל שדה נשים name ואת ngModel.

app.component.html
<h3>New Post</h3>
<form #postsForm="ngForm" ngSubmit="onPostCreate(postsForm)">
<label>Title:</label>
<input type="text" name="title" ngModel>

<label>Content:</label>
<input type="text" name="content" ngModel>

<input type="submit" value="Add Post">
</form>

נגדיר את מבנה הפוסטים שלנו:

post.model.ts
export interface Post{
id: number,
title: string,
content: string
}

נשתמש בקובץ service על מנת לשלוח את הקריאה ל-API. פונקציית ה-callback מחזירה את הערך שהפונקציה מחזירה.

posts.service.ts
baseUrl = 'http://localhost:3000'

constructor(private http: HttpClient){}

createPost(post: Post){
return this.http.post(`${baseUrl}/posts`, post);
}

לפןנקציית ה-post יש פרמטר שלישי אופציונלי והוא headers שאנחנו רוצים להעביר לדף.

posts.service.ts
baseUrl = 'http://localhost:3000'

constructor(private http: HttpClient){}

createPost(post: Post){
const headers = new HttpHeaders({ 'myHeaders': 'token-value' });

return this.http.post(`${baseUrl}/posts`, post, {headers: headers});
}

נקרא ל-service בתוך הקומפוננטה.

app.component.ts
constructor(private postsService: PostsService){}

onPostCreate(post: Post){
this.http.postsService(post).subscribe((response) => {
console.log(response);
});
}
לשים לב

ללא קריאה ל-subscribe לא תהיה קריאה לפונקציית ה-post.